//
//  PersonalDataViewController.m
//  TenThousand
//
//  Created by 我的 on 16/7/7.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "PersonalDataViewController.h"
#import "PersonTableViewCell.h"
#import "JobInformationViewController.h"//工作信息
#import "FamilyInformationViewController.h"//家庭信息
#import "InforMationModel.h"


@interface PersonalDataViewController ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIPickerViewDelegate>
{
    BXPickerView *_pickerView;
    NSString *_getText;
    
    NSMutableDictionary *_textDic;
    
    NSDateFormatter *_dateFormatter;
    UIDatePicker *_datePicker;
    UIView *_coverView ;
    
}

@property (nonatomic, strong) NSMutableArray *userInfoClassArrM;
@property (nonatomic, assign) NSInteger eduAttainment;
@property (nonatomic, strong) NSMutableDictionary *userInfoDicM;

@end

#define PERSONALARR @[@"姓名",@"邀请码",@"性别",@"邮箱",@"QQ",@"教育程度",@"工作信息",@"家庭信息"]
#define INFORMATION @[@"请填写真是姓名",@"请填写邀请码",@"女",@"请直接填写",@"请直接填写",@"本科"]
#define USERINFO @[@"请填写真是姓名",@"请填写邀请码",@"Sex",@"Email",@"QQ",@"Education"]

@implementation PersonalDataViewController

- (NSMutableArray *)userInfoClassArrM {
    if (!_userInfoClassArrM) {
        _userInfoClassArrM = [NSMutableArray array];
    }
    return _userInfoClassArrM;
}

- (NSMutableDictionary *)userInfoDicM {
    if (!_userInfoDicM) {
        _userInfoDicM = [NSMutableDictionary dictionary];
    }
    return _userInfoDicM;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //设置右按钮
    [self createLeft:[UIImage imageNamed:@"ZHSZicon_03"] leftClick:^{
        [self.navigationController popViewControllerAnimated:YES];
    } right:nil rightClick:nil];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonClick:)];
 
    
    [self.view addSubview:self.personalTableView];
    self.navigationItem.title = @"设置个人资料";
    
    _textDic = [NSMutableDictionary dictionary];
    
    self.eduAttainment = 0;
//    [self GetUserInfoUpdate];
    
    [self setRequestInfor];
}

- (void)getUserInfoClassDate:(NSString *)typeId {
    /*类型 TypeId
     0.工作情况 1.教育情况  2.企业性质  3.行业分类 4.住房情况*/
    NSDictionary *dict1 = @{
                            @"TypeId":typeId
                            };
    
    //用户基础信息资料读取接口
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"User.GetUserInfoClass" withParaments:dict1 withSuccessBlock:^(NSDictionary *object) {

        [self.userInfoClassArrM removeAllObjects];
        [self.userInfoClassArrM addObjectsFromArray:object[@"Data"]];
        [self showPickerView];
    } withFailureBlock:^(NSError *error) {
        
    } progress:^(float progress) {
        
    }];

}

- (void)showPickerView {
    NSMutableArray *arrM = [NSMutableArray array];
    for (NSDictionary *dic in self.userInfoClassArrM) {
        [arrM addObject:dic[@"InfoName"]];
    }
//    NSArray *arr = @[@"博士以上",@"博士",@"硕士",@"本科",@"本科以下"];
    BXPickerView *pickerView = [[BXPickerView alloc] initWithFrame:CGRectMake(0, Screen_Height-220, Screen_Width, 220) WithTitleListArr:arrM WithIndex:1];
    pickerView.clickedBtnIndexBlock = ^(NSString *text, NSInteger index){
        _getText = text;
        self.eduAttainment = index + 1;
        [_textDic setValue:_getText forKey:@"education"];//教育程度
        NSIndexSet * nd = [[NSIndexSet alloc] initWithIndex:5];//刷新第二个section
        [_personalTableView reloadSections:nd withRowAnimation:UITableViewRowAnimationAutomatic];
    };
    
    [pickerView showView];
}


- (void)rightButtonClick:(UIBarButtonItem *)item{
 
    NSLog(@"%@",_textDic);
    
    [self GetUserInfoUpdate];
    
}

//懒加载tableView
- (UITableView *)personalTableView{
    if (!_personalTableView) {
        _personalTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-64) style:UITableViewStyleGrouped];
        _personalTableView.delegate = self;
        _personalTableView.dataSource = self;
        _personalTableView.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.00];
        _personalTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.personalTableView.showsVerticalScrollIndicator = NO;
        _personalTableView.scrollEnabled = NO;
    }
    return _personalTableView;
}

//组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 8;
}

//行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

//cell复用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PersonTableViewCell *personalCell = [tableView dequeueReusableCellWithIdentifier:@"PERSONALTABLEVIEWCELL"];
    if (personalCell == nil) {
        personalCell = [[[NSBundle mainBundle] loadNibNamed:@"PersonTableViewCell" owner:nil options:nil] lastObject];
    }
    personalCell.selectionStyle = UITableViewCellSelectionStyleNone;
    personalCell.informationLable.text = PERSONALARR[indexPath.section];
    
    //设置向右的箭头
    if (indexPath.section >2) {
        personalCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.section ==2) {
        personalCell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"add"]];
    }
    
    //文本框改为不可编辑
    if (indexPath.section == 2 || indexPath.section == 5 || indexPath.section == 6 || indexPath.section == 7) {
        personalCell.inforTextfield.enabled = NO;
    }
    
    
    if (indexPath.section < 6) {
        if (indexPath.section == 0 || indexPath.section == 1) {
            personalCell.inforTextfield.placeholder = USERINFO[indexPath.section];
        } else {
            if ([[self.userInfoDicM objectForKey:USERINFO[indexPath.section]] isEqualToString:@""]) {
                personalCell.inforTextfield.placeholder = @"请选择";
            } else {
                personalCell.inforTextfield.placeholder = [self.userInfoDicM objectForKey:USERINFO[indexPath.section]];
            }
        }
        personalCell.inforTextfield.delegate = self;
        personalCell.inforTextfield.tag = indexPath.section + 1000;
        
        //cell赋值
        personalCell.inforTextfield.text = _getText;
        
    }
    return personalCell;
}

//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 40;
}


//footer
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

//header高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (section == 0 ) {
        return 15;
    }else if(section == 2 || section == 5){
        return 25;
    }else{
        return 8;
    }
    return 0.01;
}


//点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
         case 2:
        {
            NSMutableArray *arr = (NSMutableArray *)@[@"男",@"女"];
            BXPickerView *pickerView = [[BXPickerView alloc] initWithFrame:CGRectMake(0, Screen_Height-220, Screen_Width, 220) WithTitleListArr:arr WithIndex:1];
                     //取值
             PersonTableViewCell *cell = (PersonTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
            pickerView.clickedBtnIndexBlock = ^(NSString *text, NSInteger index){
                _getText = text;
                [_textDic setValue:_getText forKey:@"Sex"];
                 cell.inforTextfield.text = _getText;
                NSIndexSet * nd=[[NSIndexSet alloc]initWithIndex:2];//刷新第二个section
                [_personalTableView reloadSections:nd withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [pickerView showView];
        }
            break;
//        case 3:
//        {
//        
//            [self datePickerSelectBirth];
//            
//        }
//            break;

            
        case 5:
        {
            //教育程度
            [self getUserInfoClassDate:@"1"];
        }
            break;
            
        case 6://跳转到工作信息页面
        {
            JobInformationViewController *jobView = [[JobInformationViewController alloc] init];
            
            jobView.ReturnJobDicBlock = ^(NSMutableDictionary *dict) {
                self.workDict = dict;
                [_textDic addEntriesFromDictionary:self.workDict];
            };
            [jobView.userInfoDicM addEntriesFromDictionary:self.userInfoDicM];
            [self.navigationController pushViewController:jobView animated:YES];
        }
            break;
            
            case 7://跳转到家庭信息页面
        {
            FamilyInformationViewController *familyView = [[FamilyInformationViewController alloc] init];
           
            familyView.ReturnDicBlock = ^(NSMutableDictionary *dict) {
                self.famDict = dict;
                [_textDic addEntriesFromDictionary:self.famDict];
               
                NSLog(@"===%@",_textDic);
            };
           
            [familyView.userInfoDicM addEntriesFromDictionary:self.userInfoDicM];
            [self.navigationController pushViewController:familyView animated:YES];
            }
            
        default:
            break;
    }
}


//textField代理方法  获取值
- (void)textFieldDidEndEditing:(UITextField *)textField{
//    if (textField.tag == 1000) {
//        [_textDic setValue:textField.text forKey:@"trueName"];//真实姓名
//    }else if (textField.tag == 1001){
//        [_textDic setValue:textField.text forKey:@"invitationCode"];
//    }else if (textField.tag == 1003){
//        [_textDic setValue:textField.text forKey:@"Email"];
//    }
//    else if (textField.tag == 1004){
//        [_textDic setValue:textField.text forKey:@"QQ"];
//    }

//    NSLog(@"%@",_textDic);
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    if (textField.tag == 1000) {
        [_textDic setValue:textField.text forKey:@"trueName"];//真实姓名
    }else if (textField.tag == 1001){
        [_textDic setValue:textField.text forKey:@"invitationCode"];
    }else if (textField.tag == 1003){
        [_textDic setValue:textField.text forKey:@"Email"];
    }
    else if (textField.tag == 1004){
        [_textDic setValue:textField.text forKey:@"QQ"];
    }
    return YES;
    
}

//通过dataPicker获取日期
- (void)datePickerSelectBirth
{
    UIView *coverView            = [[UIView alloc] initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
    _coverView = coverView;
    coverView.backgroundColor    = [UIColor colorWithRed:0.41 green:0.41 blue:0.41 alpha:0.8];
    [self.view addSubview:coverView];
    
    UIDatePicker *datePicker     = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, Screen_Height-280, Screen_Width, 220)];
    _datePicker = datePicker;
    
    datePicker.backgroundColor   = [UIColor whiteColor];
    datePicker.date              = [NSDate date];
    datePicker.datePickerMode    = UIDatePickerModeDate;
    
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中
    datePicker.locale = locale;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    _dateFormatter = dateFormatter;
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [coverView addSubview:datePicker];
    
    UIView *buttonView           = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_Height-280, Screen_Width, 44)];
    
    buttonView.backgroundColor   = [UIColor whiteColor];
    [coverView addSubview:buttonView];
    
    UIButton *cancelBtn          = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor: [UIColor colorWithRed:0.20 green:0.58 blue:0.92 alpha:1.00] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(buttonView);
        make.left.equalTo(buttonView).with.offset(16);
    }];
    
    
    UIButton *OKBtn              = [UIButton buttonWithType:UIButtonTypeCustom];
    [OKBtn setTitle:@"完成" forState:UIControlStateNormal];
    [OKBtn setTitleColor: [UIColor colorWithRed:0.20 green:0.58 blue:0.92 alpha:1.00] forState:UIControlStateNormal];
    [OKBtn addTarget:self action:@selector(OKbtn) forControlEvents:UIControlEventTouchUpInside];
    [buttonView addSubview:OKBtn];
    [OKBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(buttonView);
        make.right.equalTo(buttonView).with.offset(-16);
    }];
    
    
}

//取消
- (void)cancelBtn{
    [_coverView removeFromSuperview];
}
//确定
- (void)OKbtn{
    _getText = [_dateFormatter stringFromDate:_datePicker.date];
    NSLog(@"%@",_getText);
    [_textDic setValue:_getText forKey:@"birthday"];
    NSIndexSet * nd=[[NSIndexSet alloc]initWithIndex:3];//刷新第二个section
    [_personalTableView reloadSections:nd withRowAnimation:UITableViewRowAnimationAutomatic];
    [_coverView removeFromSuperview];
}



//所有字段全部上传  遗留
-(void)GetUserInfoUpdate{

    NSString *loginName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginName"];
    NSDictionary *para = @{
                           @"LoginName":loginName,
                           @"Email":_textDic[@"Email"] ? _textDic[@"Email"] : @"",
                           @"Sex":_textDic[@"Sex"] ? _textDic[@"Sex"] : @"",
                           @"QQ":_textDic[@"QQ"] ? _textDic[@"QQ"] : @"",
                    /*Int*/@"Education":[NSString stringWithFormat:@"%ld", self.eduAttainment == 0 ? self.eduAttainment + 1 : self.eduAttainment],
                    /*Int*/@"Housing":[NSString stringWithFormat:@"%ld", [self.famDict[@"houseInfoNum"] integerValue] == 0 ? [self.famDict[@"houseInfoNum"] integerValue] + 1 : [self.famDict[@"houseInfoNum"] integerValue]],
                    /*Int*/@"Marriage":self.famDict[@"marriage"] ? self.famDict[@"marriage"] : @"1",
                    /*Int*/@"Pretax":self.workDict[@"income"] ? self.workDict[@"income"] : @"",
                           @"SitWhere":self.workDict[@"companyAddress"] ? self.workDict[@"companyAddress"] : @"",
                           @"Compay":self.workDict[@"companyName"] ? self.workDict[@"companyName"] : @"",
                           @"Business":self.workDict[@"license"] ? self.workDict[@"license"] : @"",
                    /*Int*/@"Enterprise":[NSString stringWithFormat:@"%ld", [self.workDict[@"enterpriseNatureNum"] integerValue] == 0 ? [self.workDict[@"enterpriseNatureNum"] integerValue] + 1 : [self.workDict[@"enterpriseNatureNum"] integerValue]],
                    /*Int*/@"Industry":[NSString stringWithFormat:@"%ld", [self.workDict[@"classificationNum"] integerValue] == 0 ? [self.workDict[@"classificationNum"] integerValue] + 1 : [self.workDict[@"classificationNum"] integerValue]],
                    /*Int*/@"Working":[NSString stringWithFormat:@"%ld", [self.workDict[@"workInfoNum"] integerValue] == 0 ? [self.workDict[@"workInfoNum"] integerValue] + 1 : [self.workDict[@"workInfoNum"] integerValue]],
                           @"WorkPhone":self.workDict[@"workPhone"] ? self.workDict[@"workPhone"] : @"",
                           @"Address":self.workDict[@"companyAddress"] ? self.workDict[@"companyAddress"] : @"",
                           };

    [_textDic addEntriesFromDictionary:para];
    NSLog(@"%@",para);
    [NetWorkManager requestWithType:HttpRequestTypePost withMethodName:@"User.GetUserInfoUpdate" withParaments:(NSDictionary *)para withSuccessBlock:^(NSDictionary *object) {
        NSLog(@"%@", object);
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@", error);
    } progress:nil];
}



- (void)setRequestInfor{
//    User.GetUserInfo //查询单个用户

    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"LoginName"];
    NSDictionary *para = @{@"LoginName":userId};
    
    [NetWorkManager requestWithType:HttpRequestTypePost  withMethodName:@"User.GetUserInfo" withParaments:para withSuccessBlock:^(NSDictionary *object) {
        
        NSLog(@"%@", object);
        NSDictionary *dic = [object[@"Data"] firstObject];
        
        [self.userInfoDicM addEntriesFromDictionary:dic];

        [self.personalTableView reloadData];

        
    } withFailureBlock:^(NSError *error) {
        NSLog(@"%@",error);
    } progress:nil];
    
    
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

@end
